package org.biogroovy.io.local;

import groovy.xml.MarkupBuilder

import java.nio.file.Path

import org.biogroovy.io.AbsWriter;
import org.biogroovy.io.IWriter;
import org.biogroovy.models.Article
import org.biogroovy.models.Author
import org.biogroovy.models.Journal
import org.biogroovy.models.MeshHeading

/**
 * This class is responsible for writing Articles out as XML.
 *
 */
public class ArticleWriter extends AbsWriter<Article> implements IWriter<Article> {

	/**
	 * Constructor.
	 */
	public ArticleWriter() {
		super(".article.xml");
	}

	@Override
	public void write(Article art, OutputStream out) throws IOException {

		PrintWriter writer = new PrintWriter(out);
		MarkupBuilder xml = new MarkupBuilder(writer);

		createXML(xml, art);
	}

	@Override
	protected void createXML(MarkupBuilder xml, Article article){
		xml.article(title: art.getTitle(),

		abs:art.getAbs(),
		pmid:art.pubmedId,
		dateCompleted:art.dateCompleted,
		dateCreated:art.dateCreated,
		dateRevised:art.dateRevised,
		pagination:art.pagination){

			art.meshHeadings.each {MeshHeading heading ->
				meshHeading(name: heading.descriptorName, qualifierNames:heading.qualifierNames.flatten())
			}

			art.authors.each{ Author auth ->
				author(lastName:auth.lastname, firstName:auth.firstname, initials:auth.initials);
			}

			art.keywords.each {String key ->
				keyword(name:key);
			}

			Journal jour = art.journal;
			journal(title:jour.title, issn:jour.issn, id:jour.toIdString(), pubDate:jour.publicationDate, startPage:jour.startPage, endPage:jour.endPage, vol:jour.volume)
		}
	}

	@Override
	public void writeCollection(Collection<Article> articles, OutputStream out)
	throws IOException {

		PrintWriter writer = new PrintWriter(out);
		MarkupBuilder xml = new MarkupBuilder(writer);
		xml.articleList{
			articles.each {Article art ->
				createXML(xml, art);
			}
		}
	}
}
